﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using ArchiSimple.Windows.Model;

namespace ArchiSimple.Windows.Dao
{
    public class PlanContractResolver : DataContractResolver
    {
        private Type[] types = new Type[]
        {
            typeof(Plan),
            typeof(Wall),
            typeof(Point),
            typeof(Room),
        };

        public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
        {
            var type = this.types.FirstOrDefault(t => t.Name == typeName);

            if (type != null && typeNamespace == "http://archisimple.com")
            {
                return type;
            }
            else
            {
                return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null);
            }

        }

        public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace)
        {
            if (types.Contains(type))
            {
                XmlDictionary dictionary = new XmlDictionary();
                typeName = dictionary.Add(type.Name);
                typeNamespace = dictionary.Add("http://archisimple.com");
                return true;
            }
            else
            {
                return knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace);
            }
        }
    }
}
